﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Arbalest.Web.Helpers;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using Arbalest.Models;

namespace Arbalest.Web.Controllers
{
    public class FinancialDataController : Controller
    {
        //
        // GET: /Fundamental/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Search()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetFundamentals(string primaryIdentifier)
        {
            @ViewBag.SearchMessage = string.Format("Search results for {0}", primaryIdentifier);
            
            DataSet ds = DataHelper.SqlServer.RESEARCH_PROD_VENDOR.FetchDataSet(
                "FeedHistory.dbo.SPstkBloombergFundamentals",
                new SqlParameter("@Identifier", "690064"),
                new SqlParameter("@CutoffDate", DateTime.Today),
                new SqlParameter("@Frequency", 4)
            );

            DataTable resultDataTable = null;

            if ((ds != null) && (ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0))
                resultDataTable = ds.Tables[0];

            
            return Json(DataHelper.MakeDictionary(resultDataTable));
        }

        public ActionResult GetData()
        {
            Regex csvRegex = new Regex("([^,\"]+|\"([^\"]|\"\")*\"|^(?=,)|(?<=,)(?=,|$))");

            string downloadUrl = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nyse&render=download";

            WebClient client = new WebClient();
            string csvData = client.DownloadString(downloadUrl);

            StringReader sr = new StringReader(csvData);
            string header = sr.ReadLine(); // Skip first line; First line is header
            // TODO: something to identify if data headers is valid; (rough form of data validity)
            MatchCollection headerTokens = csvRegex.Matches(header);

            List<ExchangeCompany> exchangeCompanyList = new List<ExchangeCompany>();

            while (sr.Peek() >= 0)
            {
                string lineData = sr.ReadLine();
                if (csvRegex.IsMatch(lineData))
                {
                    MatchCollection tokens = csvRegex.Matches(lineData);
                    // Symbol	Name	LastSale	MarketCap	ADR TSO	IPOyear	Sector	industry	Summary Quote
                    //ExchangeCompany company = new ExchangeCompany()
                    //{
                    //    Exchange = "NASDAQ",
                    //    Symbol = tokens[0].Value.Trim(),
                    //    Name = tokens[0].Value.Trim(),
                    //    LastSale = 0,
                    //    MarketCap = 0,
                    //    IPOyear = tokens[0].Value.Trim(),
                    //    Sector = tokens[0].Value.Trim(),
                    //    Industry = tokens[0].Value.Trim(),
                    //    QuoteUrl = tokens[0].Value.Trim()
                    //};
                    exchangeCompanyList.Add(new ExchangeCompany()
                    {
                        Exchange = "NASDAQ",
                        Symbol = tokens[0].Value.Trim(),
                        Name = tokens[0].Value.Trim(),
                        LastSale = 0,
                        MarketCap = 0,
                        IPOyear = tokens[0].Value.Trim(),
                        Sector = tokens[0].Value.Trim(),
                        Industry = tokens[0].Value.Trim(),
                        QuoteUrl = tokens[0].Value.Trim()
                    });

                }
            }

            return View();
        }
    }
}
